﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace GuidGen.Extensions
{
    public static class ControlExtensions
    {
        public static readonly DependencyProperty ItemDoubleClickCommandProperty = DependencyProperty.RegisterAttached(
            "ItemDoubleClickCommand", typeof(ICommand), typeof(ControlExtensions), new FrameworkPropertyMetadata(OnItemDoubleClickPropertyValueChanged));

        public static ICommand GetItemDoubleClickCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(ItemDoubleClickCommandProperty);
        }

        public static void SetItemDoubleClickCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(ItemDoubleClickCommandProperty, value);
        }

        public static void OnItemDoubleClickPropertyValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var listBox = (ListBox)sender;
            if (e.OldValue != null)
            {
                listBox.MouseDoubleClick -= OnListBoxItemMouseDoubleClick;
            }
            if (e.NewValue != null)
            {
                listBox.MouseDoubleClick += OnListBoxItemMouseDoubleClick;
            }
        }

        static void OnListBoxItemMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var cmd = GetItemDoubleClickCommand((DependencyObject)sender);
            var listBox = (ListBox)sender;
            cmd.Execute(listBox.SelectedItem);
        }
    }
}